package com.hmall.order.interceptors;

import com.hmall.order.utils.UserHolder;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {
    /*前置拦截:登录拦截器*/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头
        String authorization = request.getHeader("authorization");
        if(StringUtils.isBlank(authorization)){
            //如果请求为空（用户未登录）
            response.setStatus(403);
           return false;
        }
        //转换userId
        Long userId = Long.valueOf(authorization);
        //存入threadLocal
        UserHolder.setUser(userId);
        //放行
        return true;
    }

    /*最终拦截*/
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //用完用户信息，清理
        UserHolder.removeUser();
    }
}
